<script lang="ts">
import type { MaybeRefOrGetter } from 'vue';
import { useLocale } from '~/modules/locale';
import { getCookieValue } from '~/utils';
import { useGameBreadcrumb } from '../helpers';
import GameDetail from './GameDetail.vue';
import GameRecommend from './GameRecommend.vue';
import GameView from './GameView.v2.vue';
import { useOnGamePM } from './helpers';
import GameRecord from './record/GameRecord.vue';

function useGameConfig(gameCodeFromUrl: MaybeRefOrGetter<string>) {
  const { currentRoute } = useRouter();
  const appStore = useAppStore();
  const { locale } = useLocale();
  const isAuthed = useAuthed();

  const isDev = computed(() => {
    const route = currentRoute.value;
    const gameCode = String(route.params.gameCode);
    return import.meta.env.DEV && gameCode === 'dev' && typeof route.query.url === 'string';
  });
  const configFromIframe = ref<any>();
  const gameCodeFromIframe = computed(() => configFromIframe.value?.game.code);
  const gameCode = computed(() => (isDev.value ? gameCodeFromIframe.value : toValue(gameCodeFromUrl)) || '');
  const gameUrl = computed(() => {
    const route = currentRoute.value;
    const gameDomain = appStore.handshake?.domain.game.replace(/\/$/, '');

    try {
      const url = new URL(isDev.value ? String(route.query.url) : `${gameDomain}/${toValue(gameCodeFromUrl)}`);
      isAuthed.value && url.searchParams.set('token', getCookieValue('token'));
      url.searchParams.set('locale', locale.value);
      return url.toString();
    }
    catch {
      return '';
    }
  });

  useOnGamePM('loaded', config => configFromIframe.value ??= config);

  return { isDev, gameCode, gameUrl };
}

// if (!location.href.includes('/play/dev'))
//   location.href = 'http://192.168.2.237:5001/play/dev?url=http%3A%2F%2F192.168.2.237%3A9501';
</script>

<script setup lang="ts">
const props = defineProps<{
  gameCode: string;
}>();

const appStore = useAppStore();
const { gameUrl, gameCode } = useGameConfig(() => props.gameCode);
const breadcrumbs = useGameBreadcrumb(gameCode);
onBeforeUnmount(() => {
  appStore.hiddenBalanceReason = '';
});
</script>

<template>
  <div class="page-content-w-sm *:mb-4 tablet:*:mb-6">
    <GameView v-if="props.gameCode" :gameCode="props.gameCode" />
    <GameDetail :gameCode="gameCode" />
    <GameRecommend :gameCode="gameCode" />
    <GameRecord :gameCode="gameCode" />
    <TBreadcrumb class="mt-8 !mb-0 tablet:mt-20" :routes="breadcrumbs" />
  </div>
</template>
